package GUILayer;
import ControlLayer.CtrMain;
import ModelLayer.Product;
import ModelLayer.Customer;
import ModelLayer.Currency;
import DBLayer.Constants;
import javax.swing.table.DefaultTableModel;
import java.awt.event.*;
import java.util.HashMap;

public class UIAddOrder extends javax.swing.JFrame {
    private CtrMain ctrMain;
    private Customer customer = new Customer();
    private Currency currency = new Currency();

    public UIAddOrder() {
        initComponents();
        ctrMain = CtrMain.getInstance();
        this.setTitle("Opret Ordre");
        //Get cash customer object.
        customer = ctrMain.getCustomerByID(Constants.CASH_CUSTOMER);
        cmbCustomer.addItem(makeObj(customer.getFirstname() + " " + customer.getLastname()));
        //Get default currency object.
        currency = ctrMain.getCurrencyByID(Constants.DEFAULT_CURRENCY);
        cmbCurrency.addItem(makeObj(currency.getIsoCode()));
        txtEan13.requestFocus();
    }

    //Creates objects for adding elements to comboboxes.
    private Object makeObj(final String item) {
        return new Object() {@Override public String toString() { return item; } };
    }

    //Refreshes product table, totalprice and taxes in the order form.
    private void loadOrderContent() {
        ((DefaultTableModel)tblOrderProductList.getModel()).setRowCount(0);
        HashMap<String, Integer> productMap = ctrMain.getProductMap();

        //Add each product to the product table.
        for (String key : productMap.keySet()) {
            Product product = ctrMain.getProductByEan13(key);
            ((DefaultTableModel)tblOrderProductList.getModel()).addRow(
                new Object [] {
                    product.getIDProduct(),
                    product.getName(),
                    product.getPrice(),
                    productMap.get(key),
                    product.getReference()
                }
            );
        }

        //Refresh total price.
        txtTotalPrice.setText(Float.toString(ctrMain.getTotalPrice()));
        //Refresh total taxes.
        txtTotalTax.setText(Float.toString(ctrMain.getTotalTax()));
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lblCustomer = new javax.swing.JLabel();
        cmbCustomer = new javax.swing.JComboBox();
        btnAddCustomer = new javax.swing.JButton();
        lblCurrency = new javax.swing.JLabel();
        cmbCurrency = new javax.swing.JComboBox();
        lblTotalPrice = new javax.swing.JLabel();
        txtTotalPrice = new javax.swing.JTextField();
        lblTotalTax = new javax.swing.JLabel();
        txtTotalTax = new javax.swing.JTextField();
        lblDiscount = new javax.swing.JLabel();
        txtDiscount = new javax.swing.JTextField();
        lblScanProduct = new javax.swing.JLabel();
        txtEan13 = new javax.swing.JTextField();
        btnCloseOrder = new javax.swing.JButton();
        scrlOrderDetailList = new javax.swing.JScrollPane();
        tblOrderProductList = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        lblCustomer.setText("Kunde:");
        lblCustomer.setFocusable(false);

        cmbCustomer.setEnabled(false);
        cmbCustomer.setFocusable(false);

        btnAddCustomer.setText("Opret ny kunde");
        btnAddCustomer.setEnabled(false);
        btnAddCustomer.setFocusable(false);

        lblCurrency.setText("Valuta:");
        lblCurrency.setFocusable(false);

        cmbCurrency.setEnabled(false);
        cmbCurrency.setFocusable(false);

        lblTotalPrice.setText("Total:");
        lblTotalPrice.setFocusable(false);

        txtTotalPrice.setEditable(false);
        txtTotalPrice.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        txtTotalPrice.setText("0.00");
        txtTotalPrice.setFocusable(false);

        lblTotalTax.setText("Heraf moms:");
        lblTotalTax.setFocusable(false);

        txtTotalTax.setEditable(false);
        txtTotalTax.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        txtTotalTax.setText("0.00");
        txtTotalTax.setFocusable(false);

        lblDiscount.setText("Rabat:");
        lblDiscount.setFocusable(false);

        txtDiscount.setEditable(false);
        txtDiscount.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        txtDiscount.setText("0.00");
        txtDiscount.setFocusable(false);

        lblScanProduct.setText("Scan vare:");

        txtEan13.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtEan13KeyPressed(evt);
            }
        });

        btnCloseOrder.setText("Afslut Ordre");
        btnCloseOrder.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCloseOrderActionPerformed(evt);
            }
        });

        tblOrderProductList.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "ID", "Name", "Price", "Quantity", "Reference"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class, java.lang.Float.class, java.lang.Integer.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tblOrderProductList.setFocusable(false);
        scrlOrderDetailList.setViewportView(tblOrderProductList);
        tblOrderProductList.getColumnModel().getColumn(0).setPreferredWidth(40);
        tblOrderProductList.getColumnModel().getColumn(1).setPreferredWidth(220);
        tblOrderProductList.getColumnModel().getColumn(2).setPreferredWidth(50);
        tblOrderProductList.getColumnModel().getColumn(3).setPreferredWidth(50);
        tblOrderProductList.getColumnModel().getColumn(4).setPreferredWidth(120);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(btnCloseOrder, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(txtEan13)
                    .addComponent(lblScanProduct, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(txtDiscount)
                    .addComponent(lblDiscount, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(txtTotalTax)
                    .addComponent(lblTotalTax, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(lblCustomer)
                    .addComponent(txtTotalPrice)
                    .addComponent(lblTotalPrice, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(cmbCurrency, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(lblCurrency, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnAddCustomer, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(cmbCustomer, 0, 108, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(scrlOrderDetailList, javax.swing.GroupLayout.DEFAULT_SIZE, 439, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(scrlOrderDetailList, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 346, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(lblCustomer)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cmbCustomer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnAddCustomer)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(lblCurrency)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cmbCurrency, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(lblTotalPrice)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtTotalPrice, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lblTotalTax)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtTotalTax, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lblDiscount)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtDiscount, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lblScanProduct)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtEan13, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnCloseOrder)))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    //Checks for "Enter" in the ean13 textField, and adds the product to the order list.
    private void txtEan13KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtEan13KeyPressed
        int key = evt.getKeyCode();
        //Check the pressed key.
        if (key == KeyEvent.VK_ENTER) {
            //Add product to order list, and refresh form content on success.
            if (ctrMain.addProduct(txtEan13.getText()) == true) {
                loadOrderContent();
            }
            txtEan13.setText(null);
        }
    }//GEN-LAST:event_txtEan13KeyPressed

    //Completes the order and writes to the database.
    private void btnCloseOrderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCloseOrderActionPerformed
        System.out.println("Ordrenr. " + ctrMain.createOrder() + " tilføjet.");
        loadOrderContent();
    }//GEN-LAST:event_btnCloseOrderActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAddCustomer;
    private javax.swing.JButton btnCloseOrder;
    private javax.swing.JComboBox cmbCurrency;
    private javax.swing.JComboBox cmbCustomer;
    private javax.swing.JLabel lblCurrency;
    private javax.swing.JLabel lblCustomer;
    private javax.swing.JLabel lblDiscount;
    private javax.swing.JLabel lblScanProduct;
    private javax.swing.JLabel lblTotalPrice;
    private javax.swing.JLabel lblTotalTax;
    private javax.swing.JScrollPane scrlOrderDetailList;
    private javax.swing.JTable tblOrderProductList;
    private javax.swing.JTextField txtDiscount;
    private javax.swing.JTextField txtEan13;
    private javax.swing.JTextField txtTotalPrice;
    private javax.swing.JTextField txtTotalTax;
    // End of variables declaration//GEN-END:variables

}
